<!--
    分页组件
    @author: zhaozj
-->
<template>
    <el-pagination
        v-model:current-page="state.currentPage"
        v-model:page-size="state.pageSize"
        :total="state.totalRows"
        :page-sizes="pageSizes"
        :background="background"
        :layout="layout"
        size="small"
        style="justify-content: end;"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
</template>

<script lang="ts">
export interface Props {
    type?: string
    background?: boolean
    pageSizes?: number[]
    pageData?: any
}
</script>

<script lang="ts" setup>
import { reactive, computed, watchEffect } from 'vue'

const props = withDefaults(defineProps<Props>(), {
    pageSizes: () => [10, 15, 20, 30, 50],
    background: true,
    pageData: () => ({})
})

const state = reactive({
    currentPage: 1,
    pageSize: 10,
    totalRows: 0
})

const layout = computed(() => {
    let arr: string[] = [];
        if (props.type === 'simple') {
            arr = ['prev', 'pager', 'next', 'total', 'sizes'];
        } else if (props.type === 'mini') {
            arr = [ 'prev', 'pager', 'next'];
        } else {
            arr = ['total', 'sizes', 'prev', 'pager', 'next', 'jumper'];
        }
        if (props.pageData.totalRows === 0) {
            arr = arr.slice(0, 1);
        }
        return arr.join(', ');
})

const emit = defineEmits(['change'])
// 切换页面条数
const handleSizeChange = (val: number) => {
    state.currentPage = 1; // 修复 当在最大页数，切换size, size数小于之前的最大数时，会同时 触发 handleCurrentChange事件
    emit('change', {pageSize: val, currentPage: 1})
}
// 切换分页
const handleCurrentChange = (val: number) => {
    emit('change', {currentPage: val})
}

watchEffect(() => {
    state.currentPage = props.pageData.pageNum
    state.pageSize = props.pageData.pageSize
    state.totalRows = props.pageData.totalRows
})
</script>
